/**
 * @author SilverBiology, LLC
 * @website http://code.google.com/p/gbif-spreadsheet-processor/
*/
Ext.namespace('GBIF');
Ext.namespace('GBIF.GeoSpatial')

GBIF.GeoSpatial.WMSCapabilitiesGrid = function(config){	
	var sm = new Ext.grid.CheckboxSelectionModel({
		listeners: {
			selectionchange:{
					scope:this
				,	fn: function(){
						this.fireEvent('selectionChanged',this,this);
					}	
			}
		}
	}); 
    
	var store = new GeoExt.data.WMSCapabilitiesStore({
			url: '../resources/api/getcapabilities-proxy.php'
		,	fields: [
					{name:'title',type:'string', mapping:"title"}
				,	{name:'name',type:'string', mapping:"name"}
				,	{name:'queryable',type:'string', mapping:"queryable"}
				,	{name:'abstract',type:'string', mapping:"abstract"}
				,	{name:'format',type:'string', mapping:"capability.request.getmap.format"}
				, {name:'metadataURLs'}
			] 
		,	listeners: {
			load: function(store, items) {
				Ext.each(items, function(tItem) {
					if (tItem.data.metadataURLs[0]) {
						tItem.data.onlineResource = tItem.data.metadataURLs[0].href;
					}					
				});
			}
		}
	});
    
	Ext.apply(this,config,{
			title: "WMS Capabilities"
		,	store: store
		,	sm: sm
		,	loadMask:true
		,	columns: [
					sm
				,	{header: "Title", dataIndex: "title", sortable: true}
				,	{header: "Name", dataIndex: "name", sortable: true, hidden:true}
				,	{header: "Queryable", dataIndex: "queryable", sortable: true, width: 70}
				,	{id: "description", header: "Description", dataIndex: "abstract"}
				,	{header: "Format", dataIndex: "format", sortable: true}
	   	]
		,	autoExpandColumn: "description"	
		,	listeners: {
				rowcontextmenu: this.previewmenu 
			}		
	});
	
	GBIF.GeoSpatial.WMSCapabilitiesGrid.superclass.constructor.call(this, config);
};

Ext.extend(GBIF.GeoSpatial.WMSCapabilitiesGrid,Ext.grid.GridPanel, {
	
		layerData: function(){
			if (this.getSelectionModel().getSelected()) {
				var rowdata = this.getSelectionModel().getSelections();
				this.fireEvent('addLayer', rowdata,this);
			} else {
				GBIF.GeoSpatial.Notice.msg(this.txtError,this.txtLayerTypeError);
			}
		}
		
	,	previewmenu:function(grid, index, e){
			var indexI = index;
			var menu = new Ext.menu.Menu({
				items: [{
						text: 'Preview'
					, scope: this
					,	handler: function(){
							this.getSelectionModel().selectRow(indexI,true);
							var rowdata = this.store.getAt(index);
							rowdata.data.layer.params.TRANSPARENT = "TRUE";
							this.fireEvent('previewLayers', rowdata, this);
						}
					}]
			});

			var rowdata = this.store.getAt(index);
			if (rowdata.data.onlineResource) {
				menu.add({
						text: 'Online Resource'
					, scope: rowdata
					,	handler: function(){
							window.open(this.data.onlineResource, '_blank');
						}
				});
			}

			e.stopEvent();
			menu.showAt(e.getXY());
		}	
});